package com.rent.message.config;

import com.rent.message.interceptor.StompChannelAuthInterceptor;
import com.rent.message.interceptor.WebSocketAuthInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class MessageWebSocketConfig implements WebSocketMessageBrokerConfigurer {


    @Autowired
    private WebSocketAuthInterceptor webSocketAuthInterceptor;

    @Autowired
    private StompChannelAuthInterceptor stompChannelAuthInterceptor;

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 你的消息系统WebSocket端点
        registry.addEndpoint("/ws")
                .setAllowedOrigins("*")
                .addInterceptors(webSocketAuthInterceptor) // 添加握手拦截器
                .withSockJS();

        // 你的消息系统WebSocket端点
        registry.addEndpoint("/ws")
                .setAllowedOrigins("*")
                .addInterceptors(webSocketAuthInterceptor);
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 客户端可以订阅的目的地（消息代理）
        registry.enableSimpleBroker("/topic", "/queue","/user");

        // 客户端发送消息到服务端的前缀
        registry.setApplicationDestinationPrefixes("/app");

        // 用户私信目的地前缀
        registry.setUserDestinationPrefix("/user");
    }


    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        // 添加STOMP消息通道拦截器
        registration.interceptors(stompChannelAuthInterceptor);
    }
}